package com.situ.store.controller;

import com.situ.store.entity.LoginLog;
import com.situ.store.service.LoginLogService;
import com.situ.store.service.UserService;
import com.situ.store.service.impl.LoginLogServiceImpl;
import com.situ.store.service.impl.UserServiceImpl;
import com.situ.store.vo.ResVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService ser = new UserServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String captcha = req.getParameter("captcha");

		if (!((String)(req.getSession().getAttribute("code"))).equals(captcha)){
			req.setAttribute("msg", "验证码错误，请重新输入!");
			req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req, resp);
		} else {
			ResVO vo = ser.check(username, password, req.getSession());
			if (vo.getCode() == 0) {
				LoginLogService ser = new LoginLogServiceImpl();
				System.out.println("登陆成功！");
				LoginLog loginLog = new LoginLog();
				loginLog.setLoginName(username);
				ser.loginLog(loginLog);
				resp.sendRedirect("/main");
			} else {
				req.setAttribute("msg", "用户名或密码错误！");
				req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req, resp);
			}
		}

	}

}
